package bezier;

import java.util.ArrayList;
import java.util.List;

public class BezierHelper {
	private List<Point> curvePoints;
	private List<Point> supportVertexies;
	
	private int n;
	
	public BezierHelper(Point... points) {
		curvePoints = new ArrayList<Point>();
		supportVertexies = new ArrayList<Point>();
		
		System.out.println();
		
		for(Point p : points) {
			supportVertexies.add(p);
		}
		
		n = supportVertexies.size() - 1;
	}
	
	public void setCurvePoints(List<Point> curvePoints) {
		this.curvePoints = curvePoints;
	}

	public List<Point> process(double delta) {
		curvePoints.clear();
		double t = 0d;
		while(t <= 1) {
			
			Point pointToAdd = bt(t);
			curvePoints.add(pointToAdd);
			
			t += delta;
		}
		return curvePoints;
	}
	
	private Point bt(double t) {
		Point point = new Point();
		
		for(int i = 0; i <= n; i++) {
			Point p = Point.multiplyByValue(supportVertexies.get(i), bi(i, n, t));
			point = Point.add(point, p);
		}
		
		return point;
	}
	
	private double bi(int i, int n, double t) {
		double a = Math.pow(t, i) * Math.pow((1 -t), (n -i));
		double b = polinomialCoeficient(i, n); 
		return a * b;
	}
	
	private double polinomialCoeficient(int k, int n) {
		double result = factorial(n) / (factorial(k) * factorial(n - k));
		return result;
	}
	
	private int factorial(int n) {
		if(n != 0) {
			return n * factorial(n - 1);
		} 
		return 1;
	}
	
}
